﻿using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using OpenTK.Windowing.GraphicsLibraryFramework;
using ErrorCode = OpenTK.Windowing.GraphicsLibraryFramework.ErrorCode;

namespace OpenGl.Explore.FirstApp
{
    public unsafe class Application
    {
        private OpenglGraphics _graphics;

        public void Initialize()
        {
            GLFW.SetErrorCallback(ErrorCallback);
            if (!GLFW.Init())
            {
                string error;
                GLFW.GetError(out error);
                throw new Exception("GLFW init failed");
            }
            GLFW.WindowHint(WindowHintInt.ContextVersionMajor, 4);
            GLFW.WindowHint(WindowHintInt.ContextVersionMinor, 2);
            GLFW.WindowHint(WindowHintOpenGlProfile.OpenGlProfile, OpenGlProfile.Core);
        } 

        public void Run(OpenglWindow window)
        {
            GLFW.SetKeyCallback(window.Window, OnKeyEvent);
            GLFW.MakeContextCurrent(window.Window);
            GL.LoadBindings(new GLFWBindingsContext());
            _graphics = new OpenglGraphics();
            _graphics.SetupVertices();
            _graphics.SetMatrix(Matrix4.CreateOrthographic(window.Width, window.Height, -1, 1));
            while (!GLFW.WindowShouldClose(window.Window))
            {

                _graphics.Render();

                GLFW.SwapBuffers(window.Window);

                GLFW.PollEvents();
            }
            GLFW.Terminate();
        }

        private void OnKeyEvent(Window* window, Keys key, int scanCode, InputAction action, KeyModifiers mods)
        {
            if (action == InputAction.Press)
            {
                switch (key)
                {
                    case Keys.A:
                        _graphics.MoveLeft();
                        break;
                    case Keys.D:
                        _graphics.MoveRight();
                        break;
                    case Keys.W:
                        _graphics.MoveUp();
                        break;
                    case Keys.X:
                        _graphics.MoveDown();
                        break;
                }
            }
        }

        private void ErrorCallback(ErrorCode error, string description)
        {
            throw new Exception(description);
        }

    }
}
